package simorg.util;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Document;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import simorg.view.Page;
import simorg.view.WebSessionContext;

public class XslTransformer {

	
	
	public static void transform (WebSessionContext wc, Document xmlDoc, Page page) throws Exception{
		
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter( System.out, format );
	    writer.write( xmlDoc );
	    
	    
		String webroot = wc.getServlet().getServletContext().getInitParameter("webcontent_root");
		String xslFilename = webroot + "/xsl/" + page.getXslTemplate();
		System.out.println("View Template:  " + xslFilename);
		TransformerFactory factory 
		  = TransformerFactory.newInstance();

		Transformer transformer 
		  = factory.newTransformer( new StreamSource( xslFilename ) );
		
		DocumentSource source = new DocumentSource( xmlDoc );
		StreamResult result = new StreamResult( wc.getResponse().getWriter() );
		transformer.transform( source, result );
		
		
	}
}
